# 权限管理服务层
from backend.models.permission import Permission
from backend.infrastructure.database import db
from backend.config.config_manager import ConfigManager

def get_permission_list():
    """获取权限列表，基于静态配置"""
    # 获取静态配置中的权限定义
    config_manager = ConfigManager()
    permission_config = config_manager.get_config('PERMISSION_FEATURE_MAP')
    
    # 获取数据库中已存在的权限
    existing_permissions = Permission.query.all()
    existing_permission_map = {p.code: p for p in existing_permissions}
    
    # 构建完整的权限列表
    all_permissions = []
    for module_key, module in permission_config.items():
        for feature_key, feature in module['features'].items():
            permission_code = feature['permission_code']
            existing_permission = existing_permission_map.get(permission_code)
            
            if existing_permission:
                # 使用数据库中的权限记录
                permission_data = existing_permission.to_dict()
            else:
                # 创建基于静态配置的权限记录
                permission_data = {
                    'id': None,
                    'code': permission_code,
                    'name': feature['display_name'],
                    'description': feature['description'],
                    'status': 'disabled',  # 默认禁用
                    'module': module_key,
                    'feature': feature_key
                }
            
            all_permissions.append(permission_data)
    
    return all_permissions

def create_permission(data):
    """创建权限记录"""
    code = data.get('code')
    name = data.get('name')
    description = data.get('description')
    status = data.get('status', 'enabled')
    
    if not code:
        return {'success': False, 'message': '权限代码不能为空'}
    
    # 检查权限代码是否已存在
    if Permission.query.filter_by(code=code).first():
        return {'success': False, 'message': '权限代码已存在'}
    
    # 验证权限代码是否在静态配置中定义
    config_manager = ConfigManager()
    permission_config = config_manager.get_config('PERMISSION_FEATURE_MAP')
    
    permission_found = False
    for module in permission_config.values():
        for feature in module['features'].values():
            if feature['permission_code'] == code:
                permission_found = True
                break
        if permission_found:
            break
    
    if not permission_found:
        return {'success': False, 'message': '权限代码不在系统配置中'}
    
    # 创建权限记录
    permission = Permission(
        code=code,
        name=name,
        description=description,
        status=status
    )
    db.session.add(permission)
    db.session.commit()
    
    return {'success': True, 'data': permission.to_dict()}

def update_permission(permission_id, data):
    """更新权限记录"""
    # 如果permission_id是数字，按ID查找；否则按code查找
    try:
        permission_id = int(permission_id)
        permission = db.session.get(Permission, permission_id)
    except ValueError:
        # permission_id是code，按code查找
        permission = get_permission_by_code(permission_id)
    
    if not permission:
        # 如果权限不存在，尝试创建它
        return create_permission(data)
    
    # 只允许更新状态，不允许修改代码、名称和描述
    if 'status' in data:
        permission.status = data['status']
    
    db.session.commit()
    return {'success': True, 'data': permission.to_dict()}

def delete_permission(permission_id):
    """删除权限记录"""
    permission = db.session.get(Permission, permission_id)
    if not permission:
        return {'success': False, 'message': '权限不存在'}
    
    # 检查是否有角色使用该权限
    if permission.roles:
        return {'success': False, 'message': '该权限已被角色使用，无法删除'}
    
    db.session.delete(permission)
    db.session.commit()
    return {'success': True}

def get_permission_by_code(code):
    """根据权限代码获取权限"""
    return Permission.query.filter_by(code=code).first()
